// Logo管理API服务 - 支持MongoDB
const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const Authorization = require('../middleware/authorization');
const { getMongoDB } = require('../config/multi-database');

// 获取Logo列表
router.get('/logos', async (req, res) => {
    try {
        const { 
            page = 1, 
            limit = 20, 
            usageType, 
            isActive = true 
        } = req.query;

        const db = getMongoDB();
        const skip = (page - 1) * limit;
        
        // 构建查询条件
        const query = {};
        if (isActive !== undefined) query.isActive = isActive === 'true';
        if (usageType) query.usageType = usageType;
        
        // 获取总数
        const total = await db.collection('logos').countDocuments(query);
        
        // 获取数据
        const cursor = db.collection('logos')
            .find(query)
            .sort({ sortOrder: 1, createdAt: -1 })
            .skip(skip)
            .limit(parseInt(limit));
        
        const data = await cursor.toArray();
        
        res.json({
            success: true,
            data: data,
            pagination: {
                page: parseInt(page),
                limit: parseInt(limit),
                total,
                totalPages: Math.ceil(total / limit)
            }
        });
    } catch (error) {
        console.error('获取Logo列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取Logo列表失败'
        });
    }
});

// 获取当前使用的Logo（前端使用）
router.get('/logos/current', async (req, res) => {
    try {
        const { usageType = 'main' } = req.query;

        const db = getMongoDB();
        
        const logo = await db.collection('logos').findOne({ 
            usageType: usageType,
            isActive: true 
        });
        
        res.json({
            success: true,
            data: logo
        });
    } catch (error) {
        console.error('获取当前Logo失败:', error);
        res.status(500).json({
            success: false,
            message: '获取当前Logo失败'
        });
    }
});

// 获取Logo详情
router.get('/logos/:id', authenticateToken, async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const logo = await db.collection('logos').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!logo) {
            return res.status(404).json({
                success: false,
                message: 'Logo不存在'
            });
        }

        res.json({
            success: true,
            data: logo
        });
    } catch (error) {
        console.error('获取Logo详情失败:', error);
        res.status(500).json({
            success: false,
            message: '获取Logo详情失败'
        });
    }
});

// 创建Logo
router.post('/logos', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const logoData = {
            ...req.body,
            createdBy: req.user.userId,
            createdAt: new Date(),
            updatedAt: new Date()
        };

        // 验证必填字段
        if (!logoData.name || !logoData.imageUrl) {
            return res.status(400).json({
                success: false,
                message: 'Logo名称和URL为必填项'
            });
        }

        // 设置默认值
        if (!logoData.usageType) logoData.usageType = 'main';
        if (!logoData.sortOrder) logoData.sortOrder = 0;
        if (logoData.isActive === undefined) logoData.isActive = true;

        // 如果是主Logo，检查是否已存在主Logo
        if (logoData.usageType === 'main' && logoData.isActive) {
            const existingMainLogo = await db.collection('logos').findOne({ 
                usageType: 'main', 
                isActive: true 
            });
            
            if (existingMainLogo) {
                return res.status(400).json({
                    success: false,
                    message: '已存在启用的主Logo，请先禁用其他主Logo'
                });
            }
        }

        const result = await db.collection('logos').insertOne(logoData);
        const logo = { ...logoData, _id: result.insertedId };

        res.status(201).json({
            success: true,
            message: 'Logo创建成功',
            data: logo
        });
    } catch (error) {
        console.error('创建Logo失败:', error);
        res.status(500).json({
            success: false,
            message: '创建Logo失败'
        });
    }
});

// 更新Logo
router.put('/logos/:id', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const logo = await db.collection('logos').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!logo) {
            return res.status(404).json({
                success: false,
                message: 'Logo不存在'
            });
        }

        const updateData = {
            ...req.body,
            updatedAt: new Date()
        };

        // 如果是主Logo且要启用，检查是否已存在其他主Logo
        if (updateData.usageType === 'main' && updateData.isActive === true) {
            const existingMainLogo = await db.collection('logos').findOne({ 
                usageType: 'main', 
                isActive: true,
                _id: { $ne: new ObjectId(req.params.id) }
            });
            
            if (existingMainLogo) {
                return res.status(400).json({
                    success: false,
                    message: '已存在启用的主Logo，请先禁用其他主Logo'
                });
            }
        }

        const result = await db.collection('logos').findOneAndUpdate(
            { _id: new ObjectId(req.params.id) },
            { $set: updateData },
            { returnDocument: 'after' }
        );

        res.json({
            success: true,
            message: 'Logo更新成功',
            data: result.value
        });
    } catch (error) {
        console.error('更新Logo失败:', error);
        res.status(500).json({
            success: false,
            message: '更新Logo失败'
        });
    }
});

// 删除Logo
router.delete('/logos/:id', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const logo = await db.collection('logos').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!logo) {
            return res.status(404).json({
                success: false,
                message: 'Logo不存在'
            });
        }

        const result = await db.collection('logos').deleteOne({ 
            _id: new ObjectId(req.params.id) 
        });

        if (result.deletedCount > 0) {
            res.json({
                success: true,
                message: 'Logo删除成功'
            });
        } else {
            res.status(500).json({
                success: false,
                message: 'Logo删除失败'
            });
        }
    } catch (error) {
        console.error('删除Logo失败:', error);
        res.status(500).json({
            success: false,
            message: '删除Logo失败'
        });
    }
});

// 设置主Logo
router.post('/logos/:id/set-main', authenticateToken, Authorization.requireRole(['admin', 'editor']), async (req, res) => {
    try {
        const db = getMongoDB();
        const { ObjectId } = require('mongodb');
        
        const logo = await db.collection('logos').findOne({ 
            _id: new ObjectId(req.params.id) 
        });
        
        if (!logo) {
            return res.status(404).json({
                success: false,
                message: 'Logo不存在'
            });
        }

        const session = db.client.startSession();
        
        try {
            session.startTransaction();
            
            // 禁用所有其他主Logo
            await db.collection('logos').updateMany(
                { 
                    usageType: 'main', 
                    _id: { $ne: new ObjectId(req.params.id) } 
                },
                { $set: { isActive: false, updatedAt: new Date() } },
                { session }
            );
            
            // 启用当前Logo
            const result = await db.collection('logos').findOneAndUpdate(
                { _id: new ObjectId(req.params.id) },
                { $set: { 
                    usageType: 'main', 
                    isActive: true, 
                    updatedAt: new Date() 
                } },
                { returnDocument: 'after', session }
            );
            
            await session.commitTransaction();
            
            res.json({
                success: true,
                message: '主Logo设置成功',
                data: result.value
            });
        } catch (error) {
            await session.abortTransaction();
            throw error;
        } finally {
            await session.endSession();
        }
    } catch (error) {
        console.error('设置主Logo失败:', error);
        res.status(500).json({
            success: false,
            message: '设置主Logo失败'
        });
    }
});

// 获取Logo统计
router.get('/logos/stats', authenticateToken, async (req, res) => {
    try {
        const db = getMongoDB();
        
        const pipeline = [
            {
                $group: {
                    _id: '$usageType',
                    count: { $sum: 1 },
                    active_count: {
                        $sum: { $cond: [{ $eq: ['$isActive', true] }, 1, 0] }
                    }
                }
            },
            {
                $project: {
                    usage_type: '$_id',
                    count: 1,
                    active_count: 1,
                    _id: 0
                }
            },
            { $sort: { count: -1 } }
        ];
        
        const stats = await db.collection('logos').aggregate(pipeline).toArray();
        
        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取Logo统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取Logo统计失败'
        });
    }
});

// 获取可用的Logo用途类型
router.get('/logos/usage-types', async (req, res) => {
    try {
        const usageTypes = [
            { value: 'main', label: '主Logo', description: '网站主要Logo' },
            { value: 'footer', label: '页脚Logo', description: '网站页脚Logo' },
            { value: 'favicon', label: '网站图标', description: '浏览器标签页图标' },
            { value: 'mobile', label: '移动端Logo', description: '移动端专用Logo' },
            { value: 'print', label: '打印Logo', description: '打印文档专用Logo' },
            { value: 'social', label: '社交媒体', description: '社交媒体分享专用' },
            { value: 'other', label: '其他用途', description: '其他特殊用途' }
        ];
        
        res.json({
            success: true,
            data: usageTypes
        });
    } catch (error) {
        console.error('获取Logo用途类型失败:', error);
        res.status(500).json({
            success: false,
            message: '获取Logo用途类型失败'
        });
    }
});

module.exports = router;